# -*- coding = utf-8 -*-
# @Time : 2024/6/9 17:50
# @Author : 0505200213石浪
# @File : users.py
# @Software : PyCharm
import os

from flask import request, redirect, url_for, session, jsonify, render_template

import socketio_events
import utils
from . import bp
from db_operations import Database

db = Database()


# 我的页面
@bp.route('/my/<username>')
def my_page(username):
    user = session[username]
    sql = 'SELECT * FROM movieFriends.friends WHERE user_name = %s'
    user['my_following'] = db.execute(sql, (username,))
    sql = 'SELECT * FROM movieFriends.friends WHERE friend_name = %s'
    user['my_followers'] = db.execute(sql, (username,))
    sql = 'SELECT * FROM movieFriends.friends f1 INNER JOIN movieFriends.friends f2 ON f1.user_name = f2.friend_name ' \
          'AND f1.friend_name = f2.user_name WHERE f1.user_name = %s '
    user['my_friends'] = db.execute(sql, (username,))
    count = [len(user['my_following']), len(user['my_followers']), len(user['my_friends'])]
    session[username] = user
    unread_num = utils.unread_num(username)
    return render_template("my.html", username=username, user_info=session[username], count=count,
                           unread_num=unread_num)


# 我的关注页面
@bp.route('/following/<username>')
def following(username):
    return render_template('following.html', my_following=session[username]['my_following'], username=username)


# 我的关注页面
@bp.route('/followers/<username>')
def followers(username):
    return render_template('followers.html', my_followers=session[username]['my_followers'], username=username)


# 好友页面
@bp.route('/friends/<username>')
def friends(username):
    return render_template('friends.html', my_friends=session[username]['my_friends'], username=username)


# 关注逻辑
@bp.route('/add_friend/<username>', methods=['POST'])
def add_friend(username):
    friend_name = request.json.get('friendName')
    sql = "INSERT INTO movieFriends.friends (user_name, friend_name) VALUES (%s, %s)"
    db.execute(sql, (username, friend_name))
    return jsonify({'message': '好友添加成功'})


# 取消关注逻辑
@bp.route('/cancel_follow/<username>', methods=['POST'])
def cancel_follow(username):
    friend_name = request.json.get('friendName')
    sql = "DELETE FROM movieFriends.friends WHERE user_name = %s AND friend_name = %s"
    db.execute(sql, (username, friend_name))
    return jsonify({'message': '取消关注成功'})


# 修改信息页面
@bp.route('/edit_profile/<username>')
def edit_profile(username):
    return render_template("edit_profile.html", user_info=session[username], username=username)


# 修改信息逻辑
@bp.route('/update_profile/<username>', methods=['POST'])
def update_profile(username):
    if request.method == 'POST':
        already_avatar = session[username]['avatar']
        avatar = request.files['avatar']
        if avatar.filename != '':
            avatar_path = os.path.join(bp.root_path, '../static/assets/img/Avatar', avatar.filename)
            avatar.save(avatar_path)
            sql_edit = "UPDATE movieFriends.user SET gender=%s, age=%s, signature=%s, address=%s, hobbies=%s, " \
                       "Avatar=%s WHERE username=%s "
            sava_avatar_path = "../static/assets/img/Avatar/" + avatar.filename
            info = {'gender': request.form['gender'], 'age': request.form['age'],
                    'signature': request.form['signature'], 'address': request.form['address'],
                    'hobbies': request.form['hobbies'], 'avatar': sava_avatar_path}
            params = (
                info['gender'], info['age'], info['signature'], info['address'], info['hobbies'], sava_avatar_path,
                username)
            session[username] = info
        else:
            info = {'gender': request.form['gender'], 'age': request.form['age'],
                    'signature': request.form['signature'], 'address': request.form['address'],
                    'hobbies': request.form['hobbies'], 'avatar': already_avatar}
            sql_edit = "UPDATE movieFriends.user SET gender=%s, age=%s, signature=%s, address=%s, hobbies=%s WHERE " \
                       "username=%s "
            params = (info['gender'], info['age'], info['signature'], info['address'], info['hobbies'], username)
            session[username] = info
        print(sql_edit, params)
        db.execute(sql_edit, params)
        return redirect(url_for('main.my_page', username=username))


# 消息页面
@bp.route('/message/<username>')
def message_page(username):
    return render_template('message.html', username=username)


# 获取未读消息
@bp.route('/unread-messages')
def get_unread_messages():
    username = request.args.get('username')
    no_read_message = socketio_events.no_read_message
    sql = "SELECT message FROM movieFriends.private_messages WHERE receiver_username=%s"
    manager_message = db.execute(sql, username)
    manager_message_list = []
    if username in no_read_message:
        manager_message_list = list(no_read_message[username])
        del no_read_message[username]
    if manager_message:
        for item in manager_message:
            msg = '系统消息:' + item[0]
            manager_message_list.append(msg)
    return jsonify({username: manager_message_list})



# 头像逻辑
@bp.route('/get_avatar', methods=['GET'])
def get_avatar():
    username = request.args.get('username')
    sql = "SELECT Avatar FROM movieFriends.user WHERE username = %s"
    result = db.execute(sql, (username,))
    return jsonify({'avatar_url': result[0][0]})


# 其他用户介绍页面
@bp.route('/user/<username>/<user_name>')
def user_profile(username, user_name):
    sql = "SELECT * FROM movieFriends.user WHERE username=%s"
    user_info = db.execute(sql, (user_name,))
    sql = "SELECT * FROM movieFriends.friends WHERE user_name = %s AND friend_name = %s"
    ifFollower = db.execute(sql, (username, user_name))
    count = [0, 0, 0]
    sql = 'SELECT COUNT(*) AS following_count FROM movieFriends.friends WHERE user_name = %s'
    count[0] = db.execute(sql, (user_info[0][1],))
    sql = 'SELECT COUNT(*) AS followers_count FROM movieFriends.friends WHERE friend_name = %s'
    count[1] = db.execute(sql, (user_info[0][1],))
    sql = 'SELECT COUNT(*) AS friends_count FROM movieFriends.friends f1 INNER JOIN ' \
          'movieFriends.friends f2 ON f1.user_name = f2.friend_name AND f1.friend_name = f2.user_name ' \
          'WHERE f1.user_name = %s'
    count[2] = db.execute(sql, (user_info[0][1],))
    return render_template('user_profile.html', user=user_info[0], username=username, ifFollower=ifFollower,
                           count=count)
